<?php

namespace app\common\model\user;

use think\Model;
use think\facade\Db;

class BabycarUser extends Model
{
    protected $name = 'babycar_users';
    protected $pk = 'user_id';

    /**
     * 获取用户列表
     * @param array $params 查询参数
     * @return array
     */
    public function getList($params = [])
    {
        $where = [];
        
        // 只查询未删除的用户
        $where[] = ['is_delete', '=', 0];
        
        // 按手机号搜索
        if (!empty($params['mobile'])) {
            $where[] = ['mobile', 'like', '%' . $params['mobile'] . '%'];
        }
        
        // 按昵称搜索
        if (!empty($params['nickName'])) {
            $where[] = ['nickName', 'like', '%' . $params['nickName'] . '%'];
        }

        // 构建查询
        $query = $this->where($where);
        
        // 添加排序
        $query->order('create_time', 'desc');
        
        // 执行分页查询
        $list = $query->paginate([
            'list_rows' => 10,
            'query' => $params
        ]);

        // 获取每个用户的总消费
        foreach ($list as &$user) {
            $user['total_consumption'] = $this->getUserTotalConsumption($user['user_id']);
        }

        return $list;
    }

    /**
     * 获取用户详情
     * @param int $user_id
     * @return array|null
     */
    public function getDetail($user_id)
    {
        $user = $this->where([
            'user_id' => $user_id,
            'is_delete' => 0
        ])->find();

        if ($user) {
            $user['total_consumption'] = $this->getUserTotalConsumption($user_id);
        }

        return $user;
    }

    /**
     * 获取用户总消费
     * @param int $user_id
     * @return float
     */
    public function getUserTotalConsumption($user_id)
    {
        return Db::name('babycar_order')
            ->where('user_id', $user_id)
            ->where('status', 'completed')  // 假设只有完成的订单才计入消费
            ->sum('final_fee');
    }

    /**
     * 更新用户信息
     * @param int $user_id
     * @param array $data
     * @return bool
     */
    public function updateUser($user_id, $data)
    {
        return $this->where('user_id', $user_id)->update($data);
    }

    /**
     * 软删除用户
     * @param int $user_id
     * @return bool
     */
    public function deleteUser($user_id)
    {
        return $this->where('user_id', $user_id)->update(['is_delete' => 1]);
    }
} 